`
https://leetcode.cn/problems/shift-2d-grid/
`

/**
 * @param {number[][]} grid
 * @param {number} k
 * @return {number[][]}
 */
var shiftGrid = function (grid, k) {
  // 把二维 grid 抽象成一维数组
  const m = grid.length, n = grid[0].length
  // 去除重复的次数
  const mn = m * n
  k = k % mn

  // 翻转后 k 个元素
  reverse(grid, mn - k, mn - 1)
  // 翻转前 mn - k 个元素
  reverse(grid, 0, mn - k - 1)
  // 翻转整个列表
  reverse(grid, 0, mn - 1)

  return grid
};

// 通过一维数组的索引访问二维数组的元素
function get(grid, index) {
  const n = grid[0].length
  const i = Math.floor(index / n), j = index % n
  return grid[i][j]
}

// 通过一维数组的索引修改二维数组的元素
function set(grid, index, val) {
  const n = grid[0].length
  const i = Math.floor(index / n), j = index % n
  grid[i][j] = val
}

// 翻转一维数组的索引区间元素
function reverse(grid, i, j) {
  while (i < j) {
    const temp = get(grid, i);
    set(grid, i, get(grid, j));
    set(grid, j, temp);
    i++;
    j--;
  }
};